﻿using Microsoft.EntityFrameworkCore.Migrations.Operations;
using System;
using System.Linq;
using WebAPItest.Models.Database;

namespace WebAPItest.Service
{
    public class UserService : IUserService
    {
        private readonly WebEnterpriseIIContext _db;

        public UserService(WebEnterpriseIIContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 根据用户名获取用户
        /// </summary>
        /// <returns></returns>
        public User GetUserByUserName(string userName)
        {
            //第一步  
           var user=  _db.Users.FirstOrDefault(x => x.UserName == userName);
            return user;
        }
        //服务层方法做的事    接口
        //1.传入数据          1.前端传入数据
        //2.处理数据          2.接口处理数据
        //3.返回结果          3.返回结果给前端
        public bool ExistUserByUserName(string userName)
        {
          return  _db.Users.Any(x => x.UserName == userName);
        }

        /// <summary>
        /// 添加一个新用户
        /// </summary>
        /// <returns></returns>
        public int AddNewUser(string username,string email,string nickname,string password)
        {
            var user = new User()
            {
                UserName = username,
                Email = email,
                NickName = nickname,
                Password = password,
                CreateTime = DateTime.Now,
                Salt = 0,
                UserLevel = 1,
            };
            //上下文.表名.
            _db.Users.Add(user);

            //保存更改
            var row = _db.SaveChanges();

            if(row>0) 
            return user.UserId;
            return 0;
        }
    }
}
